<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline>
      <el-form-item :label="t('sn.sn_number')">
        <el-input
          v-model="form.sn_id"
          clearable
          :placeholder="t('common.inputText')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.productName')">
        <el-input
          v-model="form.product_name"
          clearable
          :placeholder="t('common.inputText')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('address.status')">
        <el-select
          v-model="form.status"
          :placeholder="t('common.selectText')"
          clearable
          style="width: 250px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.creationTime')">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          @change="changeTime"
          :editable="false"
          unlink-panels
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">{{
          t('common.search')
        }}</el-button>
        <el-button icon="Refresh" @click="reset">{{ t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center mb-20px mt-10px">
      <el-button type="primary" @click="handleAdd">
        {{ t('sn.add_new_sn') }}
      </el-button>
      <!-- <el-button type="primary">
        {{ t('action.exportFile') }}
      </el-button> -->
      <el-button type="primary" @click="handlePrint">
        {{ t('sn.print') }}
      </el-button>
    </div>
    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column :label="t('sn.sn_number')" prop="sn_id" min-width="200" />
      <el-table-column
        :label="t('wholesalOrder.productName')"
        prop="product_name"
        min-width="200"
      />
      <el-table-column :label="t('purchase.sup')" prop="seller_name" min-width="200" />
      <el-table-column :label="t('address.status')" min-width="100" prop="status" />
      <el-table-column
        :label="t('inventory.conversion.warehouse')"
        min-width="100"
        prop="warehouse_name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('common.creator')"
        prop="creator_name"
        min-width="120"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        :label="t('common.create_time')"
        prop="create_time"
        :width="calculateColumnWidth(dataList, 'create_time')"
        :show-overflow-tooltip="true"
      />
      <el-table-column fixed="right" :label="t('common.operation')" width="180">
        <template #default="{ row }">
          <el-button @click="handleDelete(row)" size="small" v-if="row.status == '未使用'">
            {{ t('sn.discard') }}
          </el-button>
          <el-button @click="handleDetail(row)" size="small" type="success">
            {{ t('action.detail') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
    <!--    新增/编辑弹框-->
    <Add ref="dialogStaffRef" @refresh="initialize" />
  </ContentWrap>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { calculateColumnWidth } from '@/utils'
import Add from './components/add.vue'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { getSnListApi, getSnDiscardApi, getSnEnumApi } from '@/api/snManage'

const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])

const dialogStaffRef = ref()

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  sn_id: '',
  product_name: '',
  status: '',
  pageIndex: 1,
  pageSize: 20
})
const date = ref<any>([])
const statusList = ref<Array<Record<string, any>>>([])
//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getSnEnumApi({ field: 'all' })
  statusList.value = resp.data.status
}
//初始化请求
const initialize = async () => {
  try {
    tableLoading.value = true
    // 这里需要替换为实际的员工信息获取API
    // 过滤掉空字符串的属性
    const params = Object.fromEntries(
      Object.entries(form.value).filter(([_, value]) => value !== '')
    )
    const resp = await getSnListApi(params)
    dataList.value = resp.data.list
    paginationTotal.value = resp.data.total
    tableLoading.value = false
  } catch (e) {
    tableLoading.value = false
  }
}
onMounted(() => {
  getDropDownBoxInfo()
  initialize()
})
//点击新增
const handleAdd = () => {
  nextTick(() => {
    dialogStaffRef.value.getBackShow('add')
    dialogStaffRef.value.dialogVisible = true
  })
}
//点击删除
const handleDelete = (row: Record<string, any>) => {
  ElMessageBox.confirm(t('sn.discard_hint'), t('common.tip'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      let res = await getSnDiscardApi({
        sn_id: row.sn_id
      })
      if (res.code == 0) {
        ElMessage.success(t('common.success'))
        initialize()
      }
    })
    .catch(() => {})
}
const handleDetail = (row: Record<string, any>) => {
  push(`/sn/sn-manage/detail?id=${row.sn_id}`)
}
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_time = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.end_time = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.start_time = null
    form.value.end_time = null
  }
}
//重置查询项
const reset = () => {
  form.value = {
    pageIndex: 1,
    pageSize: 20
  }
  date.value = []
  initialize()
}
//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}
const handlePrint = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning(t('sn.select_sn_to_print'))
    return
  }

  // 这里调用打印API，示例代码：
  const snIds = multipleSelection.value.map((item) => item.sn_id)
  console.log('准备打印的SN号:', snIds)
  // 实际项目中这里应该调用打印机API或打开打印预览
  ElMessageBox.confirm(t('sn.print_confirm'), t('common.tip'), {
    confirmButtonText: t('confirmMessage.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      console.log('开始打印SN号:', snIds)
      // 这里调用实际的打印API
      const printData = [] as any
      multipleSelection.value.forEach((item) => {
        printData.push({
          sn_code: item.sn_id,
          product_name: item.product_name,
          lines: item.product_info
        })
      })
      const response = await fetch('http://127.0.0.1:33333/print', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(printData)
      })
      console.log('print', print)
      if (!response.ok) {
        throw new Error('打印失败')
      }
    })
    .catch(() => {
      console.log('用户取消了打印')
    })
}
</script>

<style lang="less" scoped></style>
